<template>
  <div class="coordinate-picker">
    <el-card class="tool-panel">
      <template #header>
        <div class="card-header">
          <span>坐标拾取</span>
          <el-switch v-model="isActive" />
        </div>
      </template>
      <div v-if="coordinates" class="coordinate-info">
        <p>经度: {{ coordinates.lng.toFixed(6) }}</p>
        <p>纬度: {{ coordinates.lat.toFixed(6) }}</p>
        <el-button size="small" @click="copyCoordinates">
          复制坐标
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { transform } from 'ol/proj'
import { ElMessage } from 'element-plus'

const props = defineProps({
  map: Object
})

const isActive = ref(false)
const coordinates = ref(null)
let mapClickListener = null

watch(isActive, (val) => {
  if (val) {
    mapClickListener = props.map.on('click', handleMapClick)
  } else {
    if (mapClickListener) {
      props.map.un('click', handleMapClick)
      coordinates.value = null
    }
  }
})

const handleMapClick = (evt) => {
  const coord = transform(evt.coordinate, 'EPSG:4490', 'EPSG:4326')
  coordinates.value = {
    lng: coord[0],
    lat: coord[1]
  }
}

const copyCoordinates = () => {
  if (!coordinates.value) return
  
  const text = `${coordinates.value.lng.toFixed(6)},${coordinates.value.lat.toFixed(6)}`
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('坐标已复制到剪贴板')
  })
}
</script>

<style lang="scss" scoped>
.coordinate-picker {
  position: absolute;
  top: vw(210);
  right: vw(20);
  z-index: 1000;
}

.coordinate-info {
  margin-top: vw(10);
}

.coordinate-info p {
  margin: vw(5) 0;
}
</style> 